'use strict';
const requireEx=require('yi-require');
const async = require('async');
const fs = require('fs');
const qiniu = require('yi-qiniu');

const middleware = (req, res, next)=>{
    let id=req.params.id;
    req.mongo.collection('card').findOne({_id:id},(e,r)=>{
        if (e) return res.err.mongoError(e);

        if(!r)
            return res.err.nothingToDelete();

        req.context = req.context || {};
        req.context.delFile = r;
        next();
    });

};

const handler = (req, res, next)=>{
    let delFile = req.context.delFile;
    let deleteList=[];

    //卡片图片
    deleteList.push(callback=>qiniu.removeFile(delFile.picPath,callback));
    //录音文件
    deleteList.push(callback=>qiniu.removeFile(delFile.soundPath,callback,'sl-record','http://slrec.huiwanvip.com/'));
    //二维码
    deleteList.push(callback=>qiniu.removeFile(delFile.qrcodePath,callback));
    //合成图片
    if(delFile.makedPicPath){
        let makedPicPath = './'+delFile.makedPicPath.replace(req.config.sys.resHost,'');
        if(fs.existsSync(makedPicPath))
        deleteList.push(callback=>{fs.unlink(makedPicPath,callback)});
    }

    async.auto(deleteList,(e,r0)=>{
        console.log('test:::',e,r0);
        // if(e)
        //     return res.reply({code:22000,message:e});

        let id=req.params.id;

        req.mongo.collection("card").deleteOne({_id: id}, (err, r)=> {
            if (err) return res.err.mongoError(err);
            if (r.deletedCount === 0) return res.err.nothingToDelete();
            res.reply({code:0,message:'删除成功',data:{deletedCount: r.deletedCount}});
        });
        // req.mongo.collection('card').findOneAndDelete({_id: id}, function (err, r) {
        //     if (err) return res.err.mongoError(err);
        //     r = r || {};
        //     if (!r.value)return res.err.nothingToDelete();
        //     req.mongo.collection("recycle").insertOne({
        //         collection: collectionName,
        //         on: new Date(),
        //         restore: false,
        //         row: r.value
        //     },  (err, r)=> {
        //         if (err) return res.err.mongoError(err);
        //
        //         if(callback&&typeof callback==="function")
        //             callback(req,{_id:id});
        //         // res.reply({deletedCount: 1});
        //
        //         res.reply({code:0,message:"删除成功",data:{deletedCount: 1}});
        //     })
        // })

    });

};

module.exports={
    open:false,
    description:'删除卡片',
    middleware: middleware,
    handler:handler
};
